#include "stdafx.h"

#include <MyFC/Slider.h>
#include <MyFC/Utility.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace My {

Slider::Slider()
{ 
	m_HorzGap = 6;
	m_VertGap = 3;
	m_ChannelHeight = 6;
	m_Thumb.Load("SliderThumb", "SliderThumbMask");
}

void Slider::HandlePaint(CDC * pDC, const CRect & r)
{
	SaveObjects save(pDC);

	CRect rClient = ClientRect();
	CBrush bFace; bFace.CreateSysColorBrush(COLOR_BTNFACE);	
	pDC->FillRect(&rClient, &bFace);

	pDC->Draw3dRect(&rClient, GetSysColor(COLOR_BTNHILIGHT), GetSysColor(COLOR_BTNSHADOW));

	CRect rChannel(rClient);
	rChannel.InflateRect(- m_HorzGap, - m_VertGap);
	rChannel.bottom = rChannel.top + m_Thumb.Height();
	rChannel = AlignRect(rClient, rChannel, ALIGN_CENTER);

	CPen pBlack(PS_SOLID, 1, RGB(0, 0, 0));
	CPen pShadow(PS_SOLID, 1, GetSysColor(COLOR_BTNSHADOW));
	CPen pHalfShadow(PS_SOLID, 1, My::MeanSysColor(COLOR_BTNFACE, COLOR_BTNSHADOW));

	if (ControlEnabled(this)) {
		pDC->SelectObject(&pShadow);
		pDC->MoveTo(rChannel.left, rChannel.top - 1);
		pDC->LineTo(rChannel.right, rChannel.top - 1);
		pDC->SelectObject(&pBlack);
		pDC->MoveTo(rChannel.left, rChannel.top);
		pDC->LineTo(rChannel.right, rChannel.top);
	} else {
		pDC->SelectObject(&pHalfShadow);
		pDC->MoveTo(rChannel.left, rChannel.top - 1);
		pDC->LineTo(rChannel.right, rChannel.top - 1);
		pDC->SelectObject(&pShadow);
		pDC->MoveTo(rChannel.left, rChannel.top);
		pDC->LineTo(rChannel.right, rChannel.top);
	}

	rChannel.InflateRect(-1, -1);

	m_ChannelLeft = rChannel.left;
	m_ChannelWidth = rChannel.Width();

	if (ControlEnabled(this)) {

		double value = GetValue();
		if (value < 0)
			value = 0;
		if (value > 1)
			value = 1;

		CRect rThumb(0, 0, m_Thumb.Width(), m_Thumb.Height());
		rThumb.OffsetRect(rChannel.left + int(value * m_ChannelWidth) - m_Thumb.Width() / 2, rChannel.top);

		m_Thumb.Draw(pDC, rThumb.left, rThumb.top);
	}
}

void Slider::HandleLeftDown(unsigned int flags, const CPoint & p)
{
	if (m_ChannelWidth > 0)		
		SetValue(double(p.x - m_ChannelLeft) / m_ChannelWidth);
	Widget::HandleLeftDown(flags, p);
}

bool Slider::HandleDragStart(unsigned int flags, const CPoint & p0, const CPoint & p)
{
	m_StartMouse = p0.x;
	m_StartPos = int(m_ChannelWidth * GetValue());

	return m_ChannelWidth > 0;
}

void Slider::HandleDragging(unsigned int flags, const CPoint & p)
{
	if (m_ChannelWidth > 0)
	{
		int pos = m_StartPos + p.x - m_StartMouse;
		double value = double(pos) / m_ChannelWidth;
		if (value < 0)
			value = 0;
		if (value > 1)
			value = 1;
		SetValue(value);
		Invalidate();
		Update();
	}
}

} // My